package com.woniuxy.mycollection;

/**
 * description: SxtArrayList <br>
 * date: 2022/2/2 11:40 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 实现ArrayList
 * 加扩容
 *
 * @param <E>
 */
public class SxtArrayList03<E> {
    private Object[] elementData;
    private int size;

    private static final int DEFALT_CAPACITY = 10;

    public SxtArrayList03() {
        elementData = new Object[DEFALT_CAPACITY];
    }

    public SxtArrayList03(int capacity) {
        if (capacity < 0) {
            throw new RuntimeException("容器的容量不能为负数");
        } else if (capacity == 0) {
            elementData = new Object[DEFALT_CAPACITY];
        } else {
            elementData = new Object[capacity];
        }

    }

    public void add(E element) {
        if (size == elementData.length) {
            //10-->10+10/2=15
            Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];
            System.arraycopy(elementData, 0, newArray, 0, elementData.length);
            elementData = newArray;
        }
        elementData[size++] = element;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0 ? true : false;
    }

    public void remove(E element) {
        //element,将它和所有元素挨个比较，获得第一个比较为true的，返回
        for (int i = 0; i < size; i++) {
            //容器中所有的比较操作,都是用equals而不是==
            if (element.equals(get(i))) {
                //将该元素从此处移除
                remove(i);
            }
        }
    }

    public void remove(int index) {
        //abcdefgh
        //abcefgh
        int numMoved = elementData.length - index - 1;
        if (numMoved > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        }
        elementData[--size] = null;
    }

    public E get(int index) {
        checkRange(index);
        return (E) elementData[index];
    }

    public void set(E element, int index) {
        checkRange(index);
        elementData[index] = element;
    }

    public void checkRange(int index) {
        //索引合法判断[0,size] 10  0-9
        if (index < 0 || index > size - 1) {
            //不合法
            throw new RuntimeException("索引不合法！" + index);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(elementData[i] + ",");
        }
        sb.setCharAt(sb.length() - 1, ']');
        return sb.toString();
    }

    public static void main(String[] args) {
        SxtArrayList03 s1 = new SxtArrayList03();
        for (int i = 0; i < 20; i++) {
            s1.add("ff" + i);
        }
        System.out.println(s1);
        s1.remove(1);
        System.out.println(s1);
        s1.remove("ff0");
        System.out.println(s1);
        System.out.println(s1.size);
        System.out.println(s1.isEmpty());
    }
}
